// 云函数入口文件
/**
 * 定义响应码 code
 * 0: 正常
 * 4000: 数据库操作 - Add 失败
 * 5000: 未找到 action
 * 5001: 参数缺失
 * 5001: 未查询到数据
 * 5002: 参数错误
 */
const cloud = require('wx-server-sdk');
const _ = require('lodash');
const moment = require('moment');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const command = db.command;

/**
 * 盒子抽奖活动相关函数入口
 * 入口参数：params, action
 * action
 *  FetchDetail - 获取抽奖活动详情
 *  ParticipateAction - 参与抽奖活动
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const { params, action } = event;
  console.log('Action', action);
  console.log('Params', params);
  const ActionMap = {
    FetchDetail: fetchDetail,
    ParticipateAction: participateAction,
    CommitHonoreeInfoAction: commitHonoreeInfoAction,
    FetchHonoreeInfoAction: fetchHonoreeInfoAction,
  };
  const result = await ActionMap[action](params);
  result.openid = wxContext.OPENID;
  return result;
}

/**
 * 获取抽奖活动详情
 * @param {*} params 参数
 */
async function fetchDetail(params) {
  const wxContext = cloud.getWXContext();
  console.log(params);
  const { lottery_id } = params;
  if (_.isEmpty(lottery_id)) return { code: 5001, errmsg: '缺少参数 lottery_id' };
  // 活动状态 lottery.status 0-未开始 1-待开奖 2-已开奖
  const whereParms = { _id: lottery_id };
  const res = await db.collection('box_lottery').where(whereParms).limit(1).get();
  const lottery = res.data[0];
  if (_.isEmpty(lottery)) return { code: 5002, errmsg: '未找到数据' };
  // 获取参与人员列表 participator_list
  lottery.participator_list = [];
  const participatorParams = { lottery_id };
  const participatorRes = await db.collection('box_lottery_participate').where(participatorParams).limit(7).get();
  _.forEach(participatorRes.data, item => {
    const { openid, user_info } = item;
    const user = { openid, nickname: user_info.nickName, avatar_url: user_info.avatarUrl };
    lottery.participator_list.push(user);
  });
  // 查询参与状态 participate_status 0-未参与， 1-已参与
  lottery.participate_status = _.find(lottery.participator_list, [ 'openid', wxContext.OPENID ]) ? 1 : 0;
  // 查询中奖状态（开奖结果）draw_result 0-未中奖 1-已中奖
  lottery.draw_result = 0;
  if (!_.isEmpty(lottery.winner)) lottery.draw_result = wxContext.OPENID === lottery.winner.openid ? 1 : 0;
  // 状态描述
  const status_map = { 0: '未开始', 1: '待开奖', 2: '已结束' };
  const status_color_map = { 0: 'blue', 1: '#4FC08D', 2: 'red' };
  lottery.status_text = status_map[lottery.status];
  lottery.status_text_color = status_color_map[lottery.status];
  return { code: 0, data: lottery };
}

/**
 * 参与抽奖活动
 * @param {Object} params params
 */
async function participateAction(params) {
  const openid = cloud.getWXContext().OPENID;
  const { lottery_id, lottery_code, user_info } = params;
  // 1. 校验 lottery_id
  // 2. 校验 lottery_code
  const codeStatus = await verifyCodeFunc(openid, lottery_code);
  if (codeStatus !== 0) return { code: 5002, errmsg: '抽奖码无效' };

  // 3. 保存参数抽奖数据
  const record = { openid, lottery_id, lottery_code, user_info };
  record.created_time = moment().format('YYYY-MM-DD HH:mm:ss');
  try {
    await db.collection('box_lottery_participate').add({ data: record });
  } catch (error) {
    console.error('Error', error);
    return { code: 4000, errmsg: error.message };
  }
  return { code: 0, errmsg: '参与成功' };
}

/**
 * 提交领奖人信息
 * @param {Object} params params
 */
async function commitHonoreeInfoAction(params) {
  const record = { ...params };
  record.created_time = moment().format('YYYY-MM-DD HH:mm:ss');
  console.log(record);
  try {
    await db.collection('box_lottery_honoree').add({ data: record });
    return { code: 0, errmsg: '提交成功' };
  } catch (error) {
    console.error(error);
    return { code: 4000, errmsg: '提交失败' };
  }
}

/**
 * 获取领奖人信息
 * @param {*} params params
 */
async function fetchHonoreeInfoAction(params) {
  const openid = cloud.getWXContext().OPENID;
  const { lottery_id } = params;
  const whereParams = { openid, lottery_id };
  const res = await db.collection('box_lottery_honoree').where(whereParams).limit(1).get();
  const info = res.data[0] || {};
  return { code: 0, errmsg: 'success', data: info };
}

/**
 * 校验抽奖码是否有效
 * 0 - 有效
 * 1 - 无效
 * @param {String} openid openid
 * @param {String} lotteryCode 抽奖码
 */
const verifyCodeFunc = async (openid, lotteryCode) => {
  // 1. 校验抽奖码是否有效
  // 2. 校验抽奖码是否已经被使用
  const code_res = await db.collection('box_lottery_participate').where({ lottery_code: lotteryCode }).count();
  if (code_res.total > 0) return 1;
  return 0;
}